using IGeekFan.AspNetCore.Knife4jUI;
using Microsoft.EntityFrameworkCore;
using NLog.Web;
using RBAC.Interstructrue;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api;
using System.Reflection;
using Yitter.IdGenerator;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using RBAC.Read.Api.Middlewares;
using Microsoft.Extensions.Caching.Memory;
using RBAC.Read.Api.Application.Options;
using RBAC.Read.Api.Application.Services;
using RBAC.Read.Api.Application.Interfaces;
using RBAC.Read.Api.Application.Handler;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(p =>
{
    // 指向由 <GenerateDocumentationFile>true</GenerateDocumentationFile> 生成的 XML 注释文件
    // 确保项目文件已开启生成，并与输出名一致（此处为 RBAC.Read.Api.xml）
    var path = Path.Combine(AppContext.BaseDirectory, "RBAC.Read.Api.xml");
    p.IncludeXmlComments(path, true);
});

// Weather 相关注册：
// 1) 绑定配置节 Weather 到 WeatherOptions
// 2) 注册 IMemoryCache 作为短期缓存以降低外部 API 调用
// 3) 注册命名 HttpClient("weather")，与 WeatherService 中使用的名称保持一致
// 4) 业务服务与规则引擎（Scoped 与 Singleton 的取舍：
//    WeatherService 依赖 HttpClientFactory/Cache，适合 Scoped；RiskEngine 为无状态，适合 Singleton）
builder.Services.Configure<WeatherOptions>(builder.Configuration.GetSection("Weather"));
builder.Services.AddMemoryCache();
builder.Services.AddHttpClient("weather");
builder.Services.AddScoped<IWeatherService, WeatherService>();
builder.Services.AddSingleton<IRiskEngine, RiskEngine>();

// 数据库连接工厂 (Dapper)
builder.Services.AddScoped<IDbConnectionFactory, DbConnectionFactory>();

// EF Core数据库上下文 (暂时保留)
builder.Services.AddDbContext<RBACDbContext>(x =>
{
    x.UseMySql(builder.Configuration.GetConnectionString("MySQL"), new MySqlServerVersion("5.7"));
});

//中介者
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));
// 自动映射
builder.Services.AddAutoMapper(typeof(RBACAutoMapper));
// 日志
builder.Host.UseNLog();
// 雪花id
YitIdHelper.SetIdGenerator(new IdGeneratorOptions());
// 仓储 (同时支持EF Core和Dapper)
builder.Services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));

// 生产工单 读侧服务注册
builder.Services.AddScoped<IProductionWorkOrderReadService, ProductionWorkOrderReadService>();

// JWT Authentication
var jwtKey = builder.Configuration["Jwt:Key"] ?? "SuperSecretKey_ForDemoOnly_ChangeMe";
var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? "RBAC.Read.Api";
var jwtAudience = builder.Configuration["Jwt:Audience"] ?? "RBAC.Read.Api.Client";
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey));

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.RequireHttpsMetadata = false;
    options.SaveToken = true;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateIssuerSigningKey = true,
        ValidateLifetime = true,
        ValidIssuer = jwtIssuer,
        ValidAudience = jwtAudience,
        IssuerSigningKey = signingKey,
        ClockSkew = TimeSpan.FromMinutes(1)
    };
});

var app = builder.Build();

// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
    app.UseSwagger();              // 启用 Swagger JSON 文档
    //app.UseSwaggerUI();          // 若使用原生 UI，可取消注释
    app.UseKnife4UI();             // 使用 Knife4j UI 展示接口文档
//}
// 启用静态文件服务
app.UseStaticFiles();

//跨域
app.UseCors(x => x.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod());
// 中间件顺序：鉴权 -> 业务中间件 -> 授权
// 1) Authentication 必须在 Authorization 之前
// 2) 自定义 OperationLog 放在认证后、授权前，记录用户上下文
app.UseAuthentication();
app.UseOperationLogging();
app.UseAuthorization();

app.MapControllers();

app.Run();
